import express from 'express';
import { CustomerService } from '../../service';
import type { CustomerData } from '../../types/DataTypes';

const router = express.Router();

// 获取所有客户
router.get('/', async (req, res) => {
    try {
        const customers = await CustomerService.getAllCustomers();
        res.json({
            success: true,
            data: customers,
            count: customers.length
        });
    } catch (error) {
        console.error('获取客户列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户列表失败'
        });
    }
});

// 检查用户名是否存在
router.get('/exists/:customerName', async (req, res) => {
    try {
        const { customerName } = req.params;

        if (!customerName) {
            return res.status(400).json({
                success: false,
                message: '请提供客户名'
            });
        }

        const exists = await CustomerService.customerNameExists(customerName);

        res.json({
            success: true,
            data: {
                exists: exists
            },
            message: exists ? '用户名已存在' : '用户名可用'
        });
    } catch (error) {
        console.error('检查用户名存在性失败:', error);
        res.status(500).json({
            success: false,
            message: '检查用户名存在性失败'
        });
    }
});

// 验证登陆
// 用户登录验证
router.post('/verify', async (req, res) => {
    try {
        const { customerName, customerId } = req.body;

        // 验证必填字段
        if (!customerName || !customerId) {
            return res.status(400).json({
                success: false,
                message: '客户名和客户ID为必填项'
            });
        }

        // 获取所有客户数据
        const isVerified = await CustomerService.verify(
            customerName,
            customerId
        );

        if (isVerified) {
            res.json({
                success: true,
                message: '登录成功',
                data: {
                    customerName: customerName,
                    customerId: customerId
                }
            });
        } else {
            res.status(401).json({
                success: false,
                message: '用户名或ID不正确'
            });
        }
    } catch (error) {
        console.error('用户登录验证失败:', error);
        res.status(500).json({
            success: false,
            message: '登录验证失败，请稍后重试'
        });
    }
});

// 搜索客户
router.get('/search', async (req, res) => {
    try {
        const { customerName } = req.query;

        // 至少需要一个搜索条件
        if (!customerName || typeof customerName !== 'string' ) {
            return res.status(400).json({
                success: false,
                message: '请提供客户名'
            });
        }

        const customers = await CustomerService.searchCustomersByName(customerName);

        res.json({
            success: true,
            data: customers,
            count: customers.length
        });
    } catch (error) {
        console.error('搜索客户失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索客户失败'
        });
    }
});

// 添加新客户
router.post('/', async (req, res) => {
    try {
        const { customerName, customerId }: CustomerData = req.body;

        // 验证必填字段
        if (!customerName || !customerId) {
            return res.status(400).json({
                success: false,
                message: '客户名和客户ID为必填项'
            });
        }

        const customerData: CustomerData = {
            customerName,
            customerId
        };

        const success = await CustomerService.addCustomer(customerData);

        if (success) {
            res.status(201).json({
                success: true,
                message: '客户添加成功',
                data: customerData
            });
        } else {
            res.status(500).json({
                success: false,
                message: '客户添加失败'
            });
        }
    } catch (error: any) {
        console.error('添加客户失败:', error);

        if (error.message.includes('已存在')) {
            res.status(409).json({
                success: false,
                message: error.message
            });
        } else {
            res.status(500).json({
                success: false,
                message: '添加客户失败'
            });
        }
    }
});

// 更新客户信息
router.put('/update', async (req, res) => {
    try {
        const customerData: CustomerData = req.body;

        // 验证必填字段
        if (!customerData.customerId) {
            return res.status(400).json({
                success: false,
                message: '客户ID不能为空'
            });
        }

        const success = await CustomerService.updateCustomer(customerData);

        if (success) {
            res.json({
                success: true,
                message: '客户信息更新成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '客户不存在或更新失败'
            });
        }
    } catch (error) {
        console.error('更新客户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '更新客户信息失败'
        });
    }
});

// 删除客户
router.delete('/:customerId', async (req, res) => {
    try {
        const { customerId } = req.params;

        const success = await CustomerService.deleteCustomer(customerId);

        if (success) {
            res.json({
                success: true,
                message: '客户删除成功'
            });
        } else {
            res.status(404).json({
                success: false,
                message: '客户不存在或删除失败'
            });
        }
    } catch (error) {
        console.error('删除客户失败:', error);
        res.status(500).json({
            success: false,
            message: '删除客户失败'
        });
    }
});

export default router;